﻿using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class WindowTools : MonoBehaviour
{	
	[MenuItem("Tools/Window/Refresh HideChildren")]
	public static void RefreshDefaultHideChildren()
	{
		GameObject windowObj = Selection.activeGameObject;
		if(windowObj == null)
			Debug.Log("请先选中一个窗口对象！");
		
		Window window = NGUITools.FindInParents<Window>(windowObj);
		if(window == null)
			Debug.Log("请选择一个窗口对象或其子控件！");
		else
		{
			window.RefreshDefaultHideChildren();
			Debug.Log("完成刷新！");
		}
	}
	
	[MenuItem("Tools/Window/Make Perfect Pixel UI")]
	public static void MakePerfectPixelUI()
    {
       UIManager.MakeAllUIPerfectPixel();
    }
	
	[MenuItem("Tools/Window/Hide DefualtHideChildren")]
	public static void HideDefualtHideChildren()
    {
       GameObject windowObj = Selection.activeGameObject;
		if(windowObj == null)
			Debug.Log("请先选中一个窗口对象！");
		
		Window window = NGUITools.FindInParents<Window>(windowObj);
		if(window == null)
			Debug.Log("请选择一个窗口对象或其子控件！");
		else
		{
			window.HideDefaultHideChildren();
			Debug.Log("完成隐藏！");
		}
    }
	
	[MenuItem("Tools/Window/Change Window Drag")]
	public static void ChangWindowDragScript()
    {
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				ChangWindowDrag(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
    }
	
	static void ChangWindowDrag(string objPath, Transform trans)
	{
		UIDragObject drag = trans.GetComponent<UIDragObject>();
		if(drag != null)
		{
			if(drag.target != null)
			{
				if(drag.target.name == "Offset")
				{
					UIDragWindow windowDrag = trans.gameObject.AddComponent<UIDragWindow>();
					windowDrag.target = drag.target;
					DestroyImmediate(drag, true);
				}
			}
			else
			{
				Debug.Log(objPath);
			}
		}
		
		for(int i = 0; i < trans.childCount; i++)
		{
			Transform child = trans.GetChild(i);
			ChangWindowDrag(objPath + "/" + child.name, child);
		}
	}
	
	[MenuItem("Tools/Window/Show DragObj")]
	public static void ShowDragObjs()
    {
		Debug.Log("开始设置Window Drag信息...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				ShowDragObj(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成Window Drag设置");
    }
	
	static void ShowDragObj(string objPath, Transform trans)
	{
		UIDragObject drag = trans.GetComponent<UIDragObject>();
		if(drag != null)
		{
			Debug.Log(objPath);
		}
		
		for(int i = 0; i < trans.childCount; i++)
		{
			Transform child = trans.GetChild(i);
			ShowDragObj(objPath + "/" + child.name, child);
		}
	}
	
	[MenuItem("Tools/Window/Show PopLists")]
	public static void ShowPopLists()
    {
		Debug.Log("开始设置Window PopList...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				ShowPopList(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成Window PopList设置");
    }
	
	static void ShowPopList(string objPath, Transform trans)
	{
		UIPopupList pop = trans.GetComponent<UIPopupList>();
		if(pop != null)
		{
			Debug.Log(objPath);
		}
		
		for(int i = 0; i < trans.childCount; i++)
		{
			Transform child = trans.GetChild(i);
			ShowPopList(objPath + "/" + child.name, child);
		}
	}
	
	[MenuItem("Tools/Window/Set TableHide")]
	public static void SetTableHides()
    {
		Debug.Log("开始设置Table隐藏策略...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				SetTableHide(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成设置!");
    }
	
	static void SetTableHide(string objPath, Transform trans)
	{
		UITable table = trans.GetComponent<UITable>();
		if(table != null)
		{
			if(table.hideInactive)
				table.hideInactive = false;
		}
		
		for(int i = 0; i < trans.childCount; i++)
		{
			Transform child = trans.GetChild(i);
			SetTableHide(objPath + "/" + child.name, child);
		}
	}
	
	[MenuItem("Tools/Window/Table revert")]
	public static void RevertTables()
    {
		Debug.Log("开始还原...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			GameObject gameObj = AssetDatabase.LoadMainAssetAtPath(file) as GameObject;

			string otherPath = file.Replace("GameResources/UI/Dep", "TTT/UI");
			GameObject otherObj = AssetDatabase.LoadMainAssetAtPath(otherPath) as GameObject;
		
			List<UITable> tablesOther = NGUITools.FindInChildren<UITable>(otherObj);
			List<UITable> tables = NGUITools.FindInChildren<UITable>(gameObj);
			
			for(int i = 0; i < tablesOther.Count; i++)
			{
				UITable otherTable = tablesOther[i];
				if(tables.Count < i + 1)
					break;
				
				tables[i].children.Clear();
				
				for(int j = 0; j < otherTable.children.Count; j++)
				{
					Transform trans = otherTable.children[j];
					string childPath = GetPathStr(trans, otherTable.transform);
					tables[i].children.Add(tables[i].transform.Find(childPath));
				}
			}
		}
		
		ResetMetas();
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成还原!");
    }
	
	static string GetPathStr(Transform child, Transform parent)
	{
		string path = child.name;
		Transform parentTrans = child.parent;
		while(parentTrans != parent && parentTrans != null)
		{					
			path = parentTrans.name + "/" + path;
			parentTrans = parentTrans.parent;	
		}
		
		return path;
	}
	
	[MenuItem("Tools/Window/Reset .meta")]
	public static void ResetMetas()
    {
		Transform cameraTrans = (FindSceneObjectsOfType(typeof(UICamera)) as UICamera[])[0].transform;
		if(cameraTrans == null)
			return;
		
		Debug.Log("开始重置.meta...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			GameObject gameObj = PrefabUtility.InstantiatePrefab(obj) as GameObject;			
			
			Transform windowTrans = gameObj.transform;
			windowTrans.parent = cameraTrans;
			windowTrans.localPosition = Vector3.zero;
			windowTrans.localRotation = Quaternion.identity;
			windowTrans.localScale = Vector3.one;
			
			Window window = gameObj.GetComponent<Window>();
			window.HideDefaultHideChildren();
			PrefabUtility.ReplacePrefab(gameObj, obj);
			
			DestroyImmediate(gameObj);
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成重置!");
    }
	
	[MenuItem("Tools/Window/Recored Mix Text")]
	public static void MixText()
    {		
		List<MixConfig> mixList = new List<MixConfig>();
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
		
			GameObject gameObj = AssetDatabase.LoadMainAssetAtPath(file) as GameObject;
			string windowName = gameObj.name;
//			List<UIMix> mixs = NGUITools.FindInChildren<UIMix>(gameObj);
//			foreach(UIMix mix in mixs)
//			{
//				MixConfig mixCofig = new MixConfig();
//				mixCofig.mixObj = windowName + "/" + mix.transform.parent.name + "/" + mix.gameObject.name;
//				mixCofig.mixStr = mix.text;
//				
//				mixList.Add(mixCofig);
//			}
		}
		
		XML<MixConfig>.SaveListAtPath(mixList, "Assets/mix.xml");
		
		AssetDatabase.SaveAssets();
    }
	
	[MenuItem("Tools/Window/Revert Mix Text")]
	public static void RevertMix()
    {		
		Transform cameraTrans = (FindSceneObjectsOfType(typeof(UICamera)) as UICamera[])[0].transform;
		if(cameraTrans == null)
			return;
		
		List<MixConfig> mixList = new List<MixConfig>();
		mixList = XML<MixConfig>.LoadListFromPath("Assets/mix.xml");
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
		
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			GameObject gameObj = PrefabUtility.InstantiatePrefab(obj) as GameObject;			
			
			Transform windowTrans = gameObj.transform;
			windowTrans.parent = cameraTrans;
			windowTrans.localPosition = Vector3.zero;
			windowTrans.localRotation = Quaternion.identity;
			windowTrans.localScale = Vector3.one;
			
			Window window = gameObj.GetComponent<Window>();
			window.HideDefaultHideChildren();			
			
			string windowName = gameObj.name;
//			List<UIMix> mixs = NGUITools.FindInChildren<UIMix>(gameObj);
			bool replace = false;
//			foreach(UIMix mix in mixs)
//			{
//				string mixObj = windowName + "/" + mix.transform.parent.name + "/" + mix.gameObject.name;
//				for(int i = 0; i < mixList.Count; i++)
//				{
//					MixConfig mixConfig = mixList[i];
//					if(mixObj == mixConfig.mixObj && mix.text != mixConfig.mixStr)
//					{
//						mix.text = mixConfig.mixStr;
//						mixList.RemoveAt(i);
//						replace = true;
//						break;
//					}
//				}
//			}
			
			if(replace)
				PrefabUtility.ReplacePrefab(gameObj, obj);			
			DestroyImmediate(gameObj);
		}
		
		AssetDatabase.SaveAssets();
    }
	
	[System.Serializable]
	public class MixConfig
	{
		public string mixObj;
		public string mixStr;
	}
	
	[MenuItem("Tools/Window/Check Anchor")]
	public static void CheckAnchors()
    {
		Debug.Log("开始检测Anchor...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				CheckAnchor(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成Anchor检测");
    }
	
	static void CheckAnchor(string objPath, Transform trans)
	{
		UIAnchor anchor = trans.GetComponent<UIAnchor>();
		if(anchor != null)
		{
			Transform offset = anchor.transform.FindChild("Offset");
			if(offset == null)
				Debug.Log("Anchor缺少Offset：" + objPath + " ！");
		}
		
		for(int i = 0; i < trans.childCount; i++)
		{
			Transform child = trans.GetChild(i);
			CheckAnchor(objPath + "/" + child.name, child);
		}
	}
	
	[MenuItem("Tools/Window/Set mustLoad true")]
	public static void SetMustLoadTrues()
    {
		Debug.Log("开始设置Mustload...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				SetMustLoadTrue(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成Mustload设置");
    }
	
	static void SetMustLoadTrue(string objPath, Transform trans)
	{
		List<UIWidget> widgets = NGUITools.FindInChildren<UIWidget>(trans.gameObject);
		foreach(UIWidget widget in widgets)
		{
			if(!widget.mustLoad)
				widget.mustLoad = true;
		}
	}
	
	[MenuItem("Tools/Window/Set widgets isUnload false")]
	public static void SetIsUnloadFalses()
    {
		Debug.Log("开始设置IsUnload...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				SetIsUnloadFalse(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成IsUnload设置");
    }
	
	static void SetIsUnloadFalse(string objPath, Transform trans)
	{
		List<UIWidget> widgets = NGUITools.FindInChildren<UIWidget>(trans.gameObject);
		foreach(UIWidget widget in widgets)
			widget.isUnload = false;
	}
	
	[MenuItem("Tools/Window/Set Window isUnload true")]
	public static void SetWindowIsUnloadTrues()
    {
		Debug.Log("开始设置IsUnload...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				SetWindowIsUnloadTrue(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成IsUnload设置");
    }
	
	static void SetWindowIsUnloadTrue(string objPath, Transform trans)
	{
		Window window = trans.GetComponent<Window>();
		if(window != null)
		{
			if(!window.isUnload)
			{
				window.isUnload = true;
				EditorUtility.SetDirty(window.gameObject);
				Debug.Log("已修正：" + objPath);
			}
		}
		else
		{
			Debug.LogError("窗口没有挂载Window脚本：" + objPath);
		}
	}
	
	[MenuItem("Tools/Window/Delet Null Materials")]
	public static void DeletNullMaterials()
    {
		Debug.Log("开始删除Null Materials...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				DeletNullMaterial(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成删除Null Materials");
    }
	
	static void DeletNullMaterial(string objPath, Transform trans)
	{
		List<UIWidget> widgets = NGUITools.FindInChildren<UIWidget>(trans.gameObject);
		foreach(UIWidget widget in widgets)
		{
			bool mustCheck = false;
			if(widget is UILabel)
			{
				UILabel label = widget as UILabel;
				if(label.font == null)
					mustCheck = true;
			}
			else if(widget is UISprite)
			{
				UISprite sprite = widget as UISprite;
				if(sprite.atlas == null)
					mustCheck = true;
			}
			else if(widget is UITexture)
			{
				UITexture texture = widget as UITexture;
				if(texture.material == null)
					mustCheck = true;
			}
			
			if(mustCheck && widget.material != null)
			{
				widget.material = null;
				EditorUtility.SetDirty(trans.gameObject);
			}
		}
	}
	
	[MenuItem("Tools/Window/Set packing flase")]
	public static void SetPackingFlases()
    {
		Debug.Log("开始设置packing...");
      	char[] trimEnd = (".prefab").ToCharArray();
		
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				SetPackingFlase(file.TrimEnd(trimEnd), gameObj.transform);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("完成设置packing");
    }
	
	static void SetPackingFlase(string objPath, Transform trans)
	{
		List<UIWidget> widgets = NGUITools.FindInChildren<UIWidget>(trans.gameObject);
		foreach(UIWidget widget in widgets)
		{
			if(widget.packaging)
				widget.packaging = false;
		}
	}
	
	[MenuItem("Tools/Update UI XMLS")]
	public static void UpdateUIXMLS()
    {
		UIResourcesStepDowanload.UpdateUIXMLS();
	}
	
	[MenuItem("Tools/Window/Change Box Collider")]
	public static void SetChangeBoxCollider()
    {
		UIChangedList.Clean();
		
		Debug.Log("开始设置Box Collider...");
      	char[] trimEnd = (".prefab").ToCharArray();
			
		string fileFolder = "Assets/GameResources/UI/Dep/Window/";
	 	string[] files = Directory.GetFiles(fileFolder, "*", SearchOption.AllDirectories);
        foreach(string file in files)
        {			
			if(file.Contains(".meta"))
				continue;
			
			Object obj = AssetDatabase.LoadMainAssetAtPath(file);
			
			if(obj is GameObject)
			{
				GameObject gameObj = obj as GameObject;
				SetBoxCollider(file.TrimEnd(trimEnd), gameObj.transform, file);
			}
		}
		
		AssetDatabase.SaveAssets();
		Debug.Log("Box Collider");
		
		UIChangedList.Save();
    }
	
	static void SetBoxCollider(string objPath, Transform trans, string file)
	{
		List<BoxCollider> boxColliders = NGUITools.FindInChildren<BoxCollider>(trans.gameObject);
		foreach(BoxCollider bc in boxColliders)
		{
			if(bc.size.z == 0)
			{
				bc.size = new Vector3(bc.size.x, bc.size.y, 1.0f);
				UIChangedList.Add(file);
			}
		}
	}
}
